<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="供应商编码" prop="supplierCode">
        <el-input
          v-model="queryParams.supplierCode"
          placeholder="请输入供应商编码"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入供应商名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应类型" prop="type">
        <!-- <el-input v-model="queryParams.userName" placeholder="供应类型" clearable style="width: 200px"
                    @keyup.enter="handleQuery" /> -->
        <el-select
          v-model="queryParams.type"
          class="m-2"
          placeholder="请选择供应类型"
          style="width: 200px"
        >
          <el-option
            v-for="item in mes_supplier_type"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Upload" @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table v-loading="loading" border :data="supplierList">
      <el-table-column label="序号" width="60" type="index" align="center">
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="status"
        width="80"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="供应商编码"
        align="center"
        prop="supplierCode"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template v-slot="{ row }">
          <el-button type="primary" @click="handleView(row)" link>{{
            row.supplierCode
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="供应商名称"
        align="center"
        prop="name"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="统一社会信用代码"
        align="center"
        prop="usci"
        width="180"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="供应商简称"
        align="center"
        prop="shortName"
        width="140"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="供应类型"
        align="center"
        prop="type"
        width="80"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <dict-tag :options="mes_supplier_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column
        label="供应渠道"
        align="center"
        prop="channel"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="开户银行"
        align="center"
        prop="bank"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="银行账号"
        align="center"
        prop="bankCode"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="主联系人"
        align="center"
        prop="mainContact"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="联系电话"
        align="center"
        prop="phone"
        width="150"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="创建人"
        align="center"
        prop="createBy"
        width="70"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="100"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        fixed="right"
        class-name="small-padding fixed-width"
        width="150"
      >
        <template #default="scope">
          <el-tooltip
            content="编辑"
            placement="top"
            v-if="scope.row.status == 1"
          >
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip
            content="删除"
            placement="top"
            v-if="scope.row.status == 1"
          >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDel(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-button
            link
            type="primary"
            icon="TurnOff"
            @click="handleService(scope.row)"
            >{{ scope.row.status == 0 ? "停用" : "启用" }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      style="margin-top: 0; padding-top: 0"
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup name="supplier">
import { downLoadBlob, downLoad } from "@/utils/ruoyi";
import useTagsViewStore from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();
import {
  listSupplier,
  deleteByIdSupplier,
  addSupplier,
  supplierExport,
  supplierTemplate,
} from "@/api/basicInfo/supplier.js";
const { proxy } = getCurrentInstance();
const { mes_supplier_type, sys_normal_disable } = proxy.useDict(
  "mes_supplier_type",
  "sys_normal_disable"
);
const router = useRouter();
const route = useRoute();
const supplierList = ref([]);
const loading = ref(false);
const total = ref(0);
import { ElMessage, ElMessageBox } from "element-plus";

const showSearch = ref(true);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
import { getToken } from "@/utils/auth";
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/supplier/importData",
});

if (route.query?.supplierCode) {
  queryParams.value.supplierCode = route.query.supplierCode;
  listSupplier(queryParams.value).then((res) => {
    if (res.rows.length > 0) {
      tagsViewStore.delView(route);
      setTimeout(() => {
        handleView(res.rows[0]);
      }, 0);
    }
  });
} else {
  getList();
}
// 新增
const handleAdd = () => {
  router.push("/basicInfo/supplier/details");
};
const handleEdit = (row) => {
  router.push({
    path: "/basicInfo/supplier/details",
    query: {
      id: row.pid,
      status: row.status,
      code: row.supplierCode,
    },
  });
};
// 查看
const handleView = (row) => {
  router.push({
    path: "/basicInfo/supplier/details",
    query: {
      id: row.pid,
      readonly: true,
      code: row.supplierCode,
      status: row.status,
    },
  });
};
const handleDel = (row) => {
  ElMessageBox.confirm(
    "确定要删除名称为 " + row.name + " 的供应商信息吗?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 用户点击了确定按钮
      deleteByIdSupplier({ pid: row.pid }).then((response) => {
        if (response.code == 200) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getList();
        }
      });
    })
    .catch(() => {
      //取消
    });
};
//停用启用
const handleService = (row) => {
  const state = row.status == 0 ? "1" : "0";
  const stateText = row.status == 0 ? "停用" : "启用";
  ElMessageBox.confirm(
    `确定要 ${stateText} 名称为 ${row.name} 的供应商信息吗?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    // 用户点击了确定按钮
    addSupplier({ pid: row.pid, status: state }).then((response) => {
      if (response.code === 200) {
        ElMessage({
          message: `${stateText}成功`,
          type: "success",
        });
        getList();
      }
    });
  });
};
function getList() {
  loading.value = true;
  listSupplier(queryParams.value)
    .then((response) => {
      supplierList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
// 导出
const handleExport = () => {
  proxy.download(
    "/supplier/export",
    {
      ...queryParams.value,
    },
    `供应商列表.xlsx`
  );
  // delete queryParams.value.pageNum;
  // delete queryParams.value.pageSize;
  // supplierExport(queryParams.value)
  //     .then(res => {
  //         downLoadBlob(res ,'供应商列表');
  //     })
  //     .finally(() => {
  //         // 在 finally 中重新设置 pageNum 和 pageSize
  //         queryParams.value.pageNum = 1;
  //         queryParams.value.pageSize = 10;
  //     });
};

/** 导入按钮操作 */
function handleImport() {
  upload.title = "供应商导入";
  upload.open = true;
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 下载模板操作 */
function importTemplate() {
  supplierTemplate().then((res) => {
    downLoadBlob(res, "供应商模版");
  });
}
// getList();
</script>
 